package bb.lanxing.mvp.presetner;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import com.umeng.analytics.MobclickAgent;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.adapter.mine.HistoryListAdapter;
import bb.lanxing.common.config.UmengEventConst;
import bb.lanxing.manager.RemoteServiceManager;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.model.database.Workout;
import bb.lanxing.mvp.model.HistoryModelImpl;
import bb.lanxing.mvp.model.i.IHistoryModel;
import bb.lanxing.mvp.presetner.i.IHistoryPresenter;
import bb.lanxing.mvp.view.i.IHistoryListView;
import bb.lanxing.service.SyncTaskService;
import bb.lanxing.util.Log;
import bb.lanxing.util.jsbridge.BridgeUtil;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;

public class HistoryPresenterImpl extends BasePresenter implements IHistoryPresenter {
    private static final String KEY_LAST_HISTORY_TIME = "last_history_time_";
    private static final String KEY_LAST_HISTORY_YEARS_TIME = "last_history_years_time_";
    private static final int UPDATE_HISTORY_CURRENT_YEAR_INTERVAL = 7200000;
    private static final int UPDATE_HISTORY_INTERVAL = 864000000;
    private static final int UPDATE_HISTORY_YEARS_INTERVAL = 86400000;
    private int currentYear;
    private IHistoryListView historyListView;
    private IHistoryModel historyModel = new HistoryModelImpl();

    public HistoryPresenterImpl(IHistoryListView iHistoryListView) {
        this.historyListView = iHistoryListView;
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        this.currentYear = calendar.get(1);
    }

    @Override
    public void getYears(final long userId) {
        historyListView.showRequestDialog();
//        if (App.getContext().isDebugMode()) {
        historyListView.closeRequestDialog();
        // TODO need get info from network and update
        List<Integer> list = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        list.add(currentYear - 2);
        list.add(currentYear - 1);
        list.add(currentYear);
        historyListView.loadYears(list);
//            return;
//        }

/*
        if (userId == 0) {
            this.historyModel.getUnUploadWorkoutYears(userId).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<>() {
                        @Override
                        public void onCompleted() {
                            HistoryPresenterImpl.this.historyListView.closeRequestDialog();
                        }

                        @Override
                        public void onError(Throwable th) {
                            Log.e("user_history", "getYears from local", th);
                            HistoryPresenterImpl.this.historyListView.closeRequestDialog();
                        }

                        @Override
                        public void onNext(List<Integer> list) {
                            if (list == null || list.isEmpty()) {
                                return;
                            }
                            HistoryPresenterImpl.this.historyListView.loadYears(list);
                        }
                    });
            return;
        }
*/
/*        addSubscription(
                this.historyModel.getUserYearCache(userId).observeOn(AndroidSchedulers.mainThread()).subscribe(list -> {
                    if (list == null || list.isEmpty()) {
                        return;
                    }
                    HistoryPresenterImpl.this.historyListView.closeRequestDialog();
                    HistoryPresenterImpl.this.historyListView.loadYears(list);
                }));
        SharedManager sharedManager = SharedManager.getInstance();
        if (System.currentTimeMillis() - sharedManager.getLong(KEY_LAST_HISTORY_YEARS_TIME + userId, 0L) < 86400000) {
            return;
        }*/
/*
        addSubscription(this.historyModel.getUserYearByServer(userId).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                        HistoryPresenterImpl.this.historyListView.closeRequestDialog();
                        SharedManager sharedManager2 = SharedManager.getInstance();
                        sharedManager2.setValue(HistoryPresenterImpl.KEY_LAST_HISTORY_YEARS_TIME + userId,
                                System.currentTimeMillis());
                    }

                    @Override
                    public void onError(Throwable th) {
                        HistoryPresenterImpl.this.historyListView.closeRequestDialog();
                        Log.e("user_history", "getYears from server", th);
                    }

                    @Override
                    public void onNext(List<Integer> list) {
                        if (list == null || list.isEmpty()) {
                            return;
                        }
                        HistoryPresenterImpl.this.historyListView.loadYears(list);
                    }
                }));
*/
    }

    public void getLocalHistory(final int year, final long userId, int localOrServer) {

        addSubscription(this.historyModel.getMonthData(year, userId).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                        HistoryPresenterImpl.this.historyListView.stopListRefresh();
                    }

                    @Override
                    public void onError(Throwable th) {
                        Log.e("user_history", "getMonthDesc", th);
                        HistoryPresenterImpl.this.historyListView.stopListRefresh();
                        HistoryPresenterImpl.this.historyListView.loadWorkoutList(year, null);
                    }

                    @Override
                    public void onNext(List<HistoryListAdapter.MonthDesc> list) {
                        if (list == null || list.isEmpty()) {
                            HistoryPresenterImpl.this.getServerHistory(year, userId, list);// null sst modify it
                        }
                        HistoryPresenterImpl.this.fixHotValue(year, list);
                        HistoryPresenterImpl.this.historyListView.loadWorkoutList(year, list);
//                        if (localOrServer == 2 && userId != 0)

                    }
                }));

    }

    @Override
    public void getMonthDesc(final int year, final long userId, int localOrServer) {

        if (localOrServer == 1) {// server) {
            if (userId != 0) {
                getServerHistory(year, userId, null);
            }
            HistoryPresenterImpl.this.historyListView.stopListRefresh();
        } else if (localOrServer == 0) {// local)
            getLocalHistory(year, userId, localOrServer);
        } else {// server then local)
            HashMap<String, List<Workout>> hashMap = null;
            Log.i("user_history", "request from server");

            getServerHistory(year, userId, null);

        }
    }

    @Override
    public void checkDetailToGo(Workout workout, final int i) {
        // if (workout.isFullData() || workout.getPointCounts() > 0) {
        if (checkPoints(workout, i)) {
            return;
        }
        // this.historyListView.showRequestDialog();
        return;
        // }
//        this.historyListView.showRequestDialog();
//        addSubscription(this.historyModel.requestWorkoutDetail(workout).observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<>() {
//                    @Override
//                    public void onCompleted() {
//                    }
//
//                    @Override
//                    public void onError(Throwable th) {
//                        HistoryPresenterImpl.this.historyListView.closeRequestDialog();
//                        if (th instanceof NetSubscribe.ApiException) {
//                            App.getContext().showMessage(th.getMessage());
//                        }
//                        Log.e("user_history", "checkDetailToGo --- get detail", th);
//                    }
//
//                    @Override
//                    public void onNext(Workout workout2) {
//                        if (HistoryPresenterImpl.this.checkPoints(workout2, i)) {
//                            HistoryPresenterImpl.this.historyListView.closeRequestDialog();
//                        }
//                    }
//                }));
    }

    public boolean checkPoints(final Workout workout, final int i) {
//        HistoryPresenterImpl.this.historyListView.showRequestDialog();

        long endTime = workout.getEndTime();
        long nowTime = System.currentTimeMillis();
        long timeDiff = nowTime - endTime;
        if (timeDiff < 3600000L) {
            long pointsCount = workout.computePointCounts();
            if (pointsCount > 0) {
                this.historyListView.goToDetail(workout, i);
                return true;
            }
//            HistoryPresenterImpl.this.historyListView.closeRequestDialog();

        }

        if (workout.isFullData()) {

            if (workout.getFullDataValue() > 1) {
                long pointsCount = workout.computePointCounts();
                if (pointsCount > 0) {
                    this.historyListView.goToDetail(workout, i);
//                    HistoryPresenterImpl.this.historyListView.closeRequestDialog();
                    return true;
                }

            }


        } else {
            long pointsCount = workout.computePointCounts();
            if (pointsCount > 0) {
                this.historyListView.goToDetail(workout, i);
                return true;
            }
//            HistoryPresenterImpl.this.historyListView.closeRequestDialog();
//            return true;
        }


        HistoryPresenterImpl.this.historyListView.showRequestDialog();

        addSubscription(this.historyModel.requestWorkoutPoint(workout).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable th) {
                        HistoryPresenterImpl.this.historyListView.closeRequestDialog();
                        App.getContext().showMessage(R.string.network_err_data_parse_error);
                        Log.e("user_history", "checkDetailToGo --- get points", th);
                    }

                    @Override
                    public void onNext(List<Trackpoint> list) {

                        if (list != null && list.size() > 0) {
                            workout.setPointCounts(list.size());
                            workout.setTrackPoints(list);
//                            workout.save();
                        }

                        HistoryPresenterImpl.this.historyListView.closeRequestDialog();
                        HistoryPresenterImpl.this.historyListView.goToDetail(workout, i);
                    }
                }));
        return false;
    }

    public void getServerHistory(final int year, final long userId, List<HistoryListAdapter.MonthDesc> descList) {
        HashMap<String, List<Workout>> hashMap;
        Log.i("user_history", "request from server");
        if (descList != null) {
            hashMap = new HashMap<>();
            for (HistoryListAdapter.MonthDesc monthDesc : descList) {
                hashMap.put(monthDesc.month, monthDesc.itemDataSet);
            }
        } else {
            hashMap = null;
        }
        addSubscription(this.historyModel.requestWorkout(year, userId, hashMap)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                        HistoryPresenterImpl.this.historyListView.stopListRefresh();
                    }

                    @Override
                    public void onError(Throwable th) {
                        HistoryPresenterImpl.this.historyListView.stopListRefresh();
                        Log.e("user_history", "getServerHistory", th);
                    }

                    @Override
                    public void onNext(List<HistoryListAdapter.MonthDesc> list2) {
                        HistoryPresenterImpl.this.fixHotValue(year, list2);
                        HistoryPresenterImpl.this.historyListView.loadWorkoutList(year, list2);
                        SharedManager sharedManager = SharedManager.getInstance();
                        sharedManager.setValue(
                                HistoryPresenterImpl.KEY_LAST_HISTORY_TIME + userId + BridgeUtil.UNDERLINE_STR + year,
                                System.currentTimeMillis());
                    }
                }));
    }

    public void fixHotValue(int year, List<HistoryListAdapter.MonthDesc> list) {
        int hotsMonth;
        if (!App.getContext().isUserSignin() || (hotsMonth = App.getContext().getSigninUser().getHotsMonth()) <= 0) {
            return;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        if (calendar.get(Calendar.YEAR) != year) {
            return;
        }
        int month = calendar.get(Calendar.MONTH) + 1;
        for (HistoryListAdapter.MonthDesc monthDesc : list) {
            if (Integer.valueOf(monthDesc.month).equals(month)) {
                monthDesc.credits = hotsMonth;
            }
        }
    }

    @Override
    public void syncWorkout(long j) {
        if (!App.getContext().isUserSignin()) {
            App.getContext().userSignin();
            App.getContext().showMessage(R.string.mine_toast_login_first);
        } else if (RemoteServiceManager.getInstance().isSporting()) {
            App.getContext().showMessage(R.string.mine_history_toast_stop_sport_first);
        } else {
            MobclickAgent.onEventValue(App.getContext(), UmengEventConst.WORKOUT_UPLOAD_BUTTON_CLICK, null, 1);
            SyncTaskService.startSyncService(App.getContext(), SyncTaskService.TASK_SYNC_WORKOUT, false);
        }
    }

    @Override
    public void updateMonthInfo(long j, final HistoryListAdapter.MonthDesc monthDesc) {
        addSubscription(this.historyModel.getMonthInfo(j, this.historyListView.getCurrentYear(), monthDesc.month)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable th) {
                        th.printStackTrace();
                    }

                    @Override
                    public void onNext(HistoryListAdapter.MonthDesc monthDesc2) {
                        monthDesc2.itemDataSet = monthDesc.itemDataSet;
                        HistoryPresenterImpl.this.historyListView.onMonthInfo(monthDesc2);
                    }
                }));
    }
}